package com.jiang.books.service.jpa;

import java.math.BigInteger;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.apache.log4j.Logger;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jiang.books.common.utils.annotation.AdditionalLogging;
import com.jiang.books.domain.Country;
import com.jiang.books.service.CountryService;

@Service("jpaCountryService")
@Repository
@Transactional
public class CountryServiceImpl implements CountryService {

	private static final Logger log = Logger.getRootLogger();
	
	@PersistenceContext
	private EntityManager entityManager;

	/*
	public CountryServiceImpl() {
	}
	
	public CountryServiceImpl(EntityManager entityManager) {
		log.debug("[CountryServiceImpl][JPA] CountryServiceImpl create instance");
		this.em = entityManager;
	}
    */
	
	@Override
	@AdditionalLogging
	@Transactional(readOnly=true)
	public List<Country> findAll() {
		log.info("Country#Find All Countries");
		List<Country> countries = entityManager.createNamedQuery("Country.findAll", Country.class).getResultList();
		return countries;
	}

	@Override
	@Transactional(readOnly=true)
	public Country findById(BigInteger id) {
		log.info("Country#Find Country by id: " + id);
		TypedQuery<Country> query = entityManager.createNamedQuery("Country.findById", Country.class);
		query.setParameter("id", id);
		return query.getSingleResult();
	}

	@Override
	public Country save(Country country) {
		if (country.getId() == null) { // Insert Country
			log.info("Country#Inserting new country");
			entityManager.persist(country);
		} else {                       // Update Country
			entityManager.merge(country);
			log.info("Country#Updating existing country");
		}
		log.info("Country#Country saved with id: " + country.getId());
		return country;
	}

	@Override
	public void delete(Country country) {
		Country mergedCountry = entityManager.merge(country);
		entityManager.remove(mergedCountry);
		log.info("Country#Country with id: " + country.getId() + " deleted successfully");
	}
}